home *** CD-ROM | disk | FTP | other *** search
- // grocery.cpp
- //
- // Example program uses the btree dictionary template to make a
- // grocery list. Names of grocery items and their corresponding
- // price are read in one at a time and added to the dictionary
- // until an 'x' (exit) is typed. An iterator template is then
- // created and used to cycle through the dictionary printing
- // each grocery item and running a total tally. When iteration
- // is finished, the total price of all the groceries is printed.
- //
- #include <cm/include/cmtbdict.h>
- #include <cm/include/cmstring.h>
-
- // Create typedefs to make the code easier to read and understand.
- //
- typedef CmTBTreeDictionary<CmString, float> GroceryList;
- typedef CmTAssociation<CmString, float> GroceryItem;
- typedef CmTBTreeIterator<GroceryItem> GroceryIterator;
-
- // Macros are used in place of the association's "value" and "object"
- // functions for readability.
- //
- #define NAME key
- #define PRICE object
-
- void main()
- {
- GroceryList list; // Declare dictionary.
- CmString stemp; // Temp for item name input.
- float ftemp; // Temp for item price input.
- Bool done = FALSE; // Boolean data type.
-
- while (!done) // While boolean is true,
- {
- cout << "Enter grocery item (\"x\" when done): " << flush;
- cin >> stemp; // Read a new item name.
-
- if (stemp[0] == 'x') // If "x", then finished.
- done = TRUE;
-
- else if (stemp.length()) // If not empty string,
- {
- cout << "Enter item price : " << flush;
- cin >> ftemp; // Read the item price.
- cin.ignore();
- list.addKeyAndObject(stemp, ftemp); // Add name and price to dictionary.
- }
- }
-
- cout.setf(ios::fixed, ios::floatfield); // Setup for float output.
- cout.precision(2);
- cout << endl << "Grocery List" << endl; // Print list header.
- cout << "----------------------------------------" << endl;
-
- float total = 0;
- GroceryIterator iterator(list); // Create an iterator.
- while (iterator) // While iterator is ok,
- {
- GroceryItem item = iterator++; // Get next grocery item.
- total += item.PRICE(); // Add price to running total.
- cout << item.NAME() << " $" << item.PRICE() << endl; // Print name/price.
- }
-
- cout << "----------------------------------------" << endl;
- cout << "Total cost is $" << total << endl; // Print total cost.
- }
-